<?php

namespace app\api\controller;

use think\Db;
use app\common\validate\OrderValidate;

class Order extends ApiBase
{
	
	protected $datas;

	/**
	 * 核对订单信息页
	 * @Author   Yichen
	 * @DateTime 2020-05-05T16:45:30+0800
	 * @return   [type]                   [description]
	 */
	public function checkOrder()
	{
		$this->datas = $this->params;
		$validate = new OrderValidate();
		if (!$validate->scene('check')->check($this->datas)) {
			return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
		}
		$goodsProId = $this->datas['goodsProId'];
		$userId = session('userinfo.uid');
		$addressData = Db::name('t_address')->alias('a')
			->join('t_user u', 'u.id=a.user_id', 'left')
			->where('a.user_id', $userId)
			->field('a.province,a.city,a.region,street,a.detailed,u.username,u.mobile,a.is_default isDefault')
			->select();
		$goodsData = Db::name('t_goods')->alias('g')
			->join('t_goods_property gp', 'g.id=gp.goods_id', 'left')
			->where('gp.id', $goodsProId)
			->field('gp.id goodsProId,g.name,gp.big_images image,gp.specifications_name as speName,gp.price')
			->find();
		if (empty($goodsData)) {
			return json(['code' => 0, 'msg' => '该商品已下架，敬请期待！', 'data' => []]);
		}
		return json([
			'code' => 1, 
			'msg' => '', 
			'data' => [
				'address' => $addressData, 
				'goodsInfo' => $goodsData
			]
		]);
	}


	/**
	 * 创建订单
	 * @Author   Yichen
	 * @DateTime 2020-05-04T18:44:18+0800
	 * @return   [type]                   [description]
	 */
	public function createOrder()
	{
		$this->datas = $this->params;
		$validate = new OrderValidate();
		if (!$validate->scene('create')->check($this->datas)) {
			return json(['code' => 0, 'msg' => $validate->getError(), 'data' => '']);
		}
		$userId = session('userinfo.uid');
		$goodsProId = $this->datas['goodsProId'];
		$number = $this->datas['number'];
		$goodsPrice = $this->datas['goodsPrice'];
		$addressId = $this->datas['addressId'];
		$remark = isset($this->datas['remark']) ? $this->datas['remark'] : '';
		$type = $this->datas['type'];
		$orderNo = $this->_createOrderNo();
		$comName = Db::name('t_address')->where('id', $addressId)->value('com_name');
		$OrderData = [
			'order_no' => $orderNo,
			'user_id' => $userId,
			'pay_status' => 0,
			'pay_price' => '',
			'goods_property_id' => $goodsProId,
			'goods_price' => $goodsPrice,
			'number' => $number,
			'address' => $comName,
			'trade_status' => 0,
			'remark' => $remark,
			'type' => $type,
			'create_time' => time()
		];
		Db::startTrans();
		try {
		    $orderId = Db::name('t_order')->insertGetId($OrderData);
		    $goodsInfo = Db::name('t_goods_property')->where('id', $goodsProId)->find();
		    $orderItemData = [
		    	'user_id' => $userId,
		    	'order_id' => $orderId,
		    	'number' => $number,
		    	'goods_property_id' => $goodsProId,
		    	'goods_name' => $goodsInfo['specifications_name'],
		    	'goods_price' => $goodsInfo['price'],
		    	'goods_cover_img' => $goodsInfo['big_images'],
		    	'create_time' => time()
		    ];
		    Db::name('t_order_item')->insert($orderItemData);
		    Db::commit();
		} catch (\Exception $e) {
			return json(['code' => 0, 'msg' => '订单创建失败', 'data' => '']);
		    Db::rollback();
		} 
		//调用支付宝或微信
		return json([
			'code' => 1, 
			'msg' => '订单创建成功', 
			'data' => [
				'image' => '/static/upload/banner/orderORcode.png'
			]
		]);
	}


	/**
	 * 生成订单号
	 * @Author   Yichen
	 * @DateTime 2020-05-04T19:03:20+0800
	 * @return   [type]                   [description]
	 */
	protected function _createOrderNo()
	{
		$order_id_main = date('YmdHis') . rand(10000000,99999999);
  		$order_id_len = strlen($order_id_main);
		$order_id_sum = 0;
		for($i=0; $i<$order_id_len; $i++){
			$order_id_sum += (int)(substr($order_id_main,$i,1));
		}
		$osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
		return $osn;
	}

	/**
	 * 我的订单列表
	 * @Author   Yichen
	 * @DateTime 2020-05-08T23:22:45+0800
	 * @return   [type]                   [description]
	 */
	public function orderList()
	{
		//宝贝	单价	数量 	商品操作	 实付款	交易操作
		$uid = session('userinfo.uid');
		$orderData = Db::name('t_order')->alias('o')
			->join('t_goods_property gp', 'gp.id=o.goods_property_id', 'left')
			->join('t_goods g', 'g.id=gp.goods_id', 'left')
			->where('user_id', $uid)
			->where('delete_time', 0)
			->field('o.order_no orderNo,o.goods_price price,o.number,g.name,gp.specifications_name specificationsName,o.pay_status payStatus')
			->limit(10)
			->select();
		$total = 10;	
		return json(['code' => 1, 'msg' => '', 'data' => $orderData]);
	}

	/**
	 * 删除订单
	 * @Author   Yichen
	 * @DateTime 2020-05-08T23:26:45+0800
	 * @return   [type]                   [description]
	 */
	public function delOrder()
	{
		$this->datas = $this->params;
		$orderNo = $this->datas['orderNo'];
		$result = Db::name('t_order')->where('order_no', $orderNo)->update(['delete_time' => time()]);
		if (!$result) {
			return json(['code' => 0, 'msg' => '删除失败', 'data' => '']);
		}
		return json(['code' => 1, 'msg' => '删除成功', 'data' => '']);
	}

}